package kxfang.com.find.fragment;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.core.widget.PopupWindowCompat;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.orhanobut.hawk.Hawk;
import com.previewlibrary.GPreviewBuilder;
import com.previewlibrary.ZoomMediaLoader;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;

import kxfang.com.base.fragment.MvvmLazyFragment;
import kxfang.com.base.livedatabus.LiveDatabus;
import kxfang.com.base.utils.GsonUtils;
import kxfang.com.base.viewmodel.IMvvmBaseViewModel;
import kxfang.com.common.bean.UserViewInfo;
import kxfang.com.common.config.HttpConfig;
import kxfang.com.common.constant.Constant;
import kxfang.com.common.router.RoutHub;
import kxfang.com.common.utils.DensityUtil;
import kxfang.com.common.utils.GetTimeAgo;
import kxfang.com.common.utils.HawkUtil;
import kxfang.com.common.utils.MyUtils;
import kxfang.com.common.utils.RouterUtils;
import kxfang.com.common.utils.StringTest;
import kxfang.com.common.utils.TestImageLoader;
import kxfang.com.common.utils.TextViewLinesUtil;
import kxfang.com.common.utils.TimeUtil;
import kxfang.com.find.R;
import kxfang.com.find.activity.ItFxActivity;
import kxfang.com.find.bean.FindListModel;
import kxfang.com.find.databinding.FindFragmentEncyclopediaTjBinding;
import kxfang.com.find.databinding.FindItemPersonalInformationBinding;
import kxfang.com.find.databinding.FindRvImgItemBinding;
import kxfang.com.find.databinding.FindRvLbItemBinding;
import kxfang.com.find.parameter.FindListPar;
import kxfang.com.common.parameter.NewSharePar;
import kxfang.com.find.parameter.SinglePar;
import kxfang.com.http.EasyHttp;
import kxfang.com.http.callback.SimpleCallBack;
import kxfang.com.http.exception.ApiException;

import static kxfang.com.common.router.RoutHub.FX_FIND;
import static kxfang.com.common.router.RoutHub.WEB_MAIN;

@Route(path = FX_FIND)
public class FxFragment extends MvvmLazyFragment<FindFragmentEncyclopediaTjBinding, IMvvmBaseViewModel> {

    //分页相关
    private int index = 1;//页码数
    private int size = 5;//个数
    private FindListPar findListPar = new FindListPar();

    private Boolean flat = false;
    private Boolean bl = false;
    private int classId = 0;

    private BaseQuickAdapter<FindListModel, BaseViewHolder> adapter;


    private BaseQuickAdapter<FindListModel.ImgsBean, BaseViewHolder> adapterImg;

    List<FindListModel> list = new ArrayList<>();
    List<FindListModel.ImgsBean> imgList = new ArrayList<>();
    List<String> lbList = new ArrayList<>();
    private int tvHang = 0;
    private int listHang = 0;
    private PopupWindow popupWindow = new PopupWindow();
//    private ShareModel shareModel = new ShareModel();


    private ArrayList<UserViewInfo> mThumbViewInfoList = new ArrayList<>();


    public static FxFragment newInstance(int id) {
        FxFragment fxTwoFragment = new FxFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("id", id);
        fxTwoFragment.setArguments(bundle);
        fxTwoFragment.setClassId(id);
        return fxTwoFragment;
    }

    private void setClassId(int id) {
        findListPar.setClassID(id);
        flat = false;
    }

    @Override
    public int getLayoutId() {
        return R.layout.find_fragment_encyclopedia_tj;
    }


    @Override
    protected void onFragmentFirstVisible() {
        super.onFragmentFirstVisible();
        //推荐列表参数
        findListPar.setPageSize(size);
        findListPar.setPageIndex(1);
        findListPar.setRUserID(String.valueOf(HawkUtil.getUserId()));

        loadData(findListPar);
        thisClick();
        ZoomMediaLoader.getInstance().init(new TestImageLoader());
    }


    private void init() {
        viewDataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        adapter = new BaseQuickAdapter<FindListModel, BaseViewHolder>(R.layout.find_item_personal_information, list) {
            @Override
            protected void onItemViewHolderCreated(@NotNull BaseViewHolder viewHolder, int viewType) {
                DataBindingUtil.bind(viewHolder.itemView);
            }

            @Override
            protected void convert(@NotNull BaseViewHolder baseViewHolder, @Nullable FindListModel findListModel) {
                int j = getItemPosition(findListModel);

                FindItemPersonalInformationBinding binding = baseViewHolder.getBinding();
                BaseQuickAdapter<String, BaseViewHolder> adapterLb;

                binding.rvLb.setLayoutManager(new LinearLayoutManager(getActivity()));
                adapterLb = new BaseQuickAdapter<String, BaseViewHolder>(R.layout.find_rv_lb_item, lbList) {

                    @Override
                    protected void onItemViewHolderCreated(@NotNull BaseViewHolder viewHolder, int viewType) {
                        DataBindingUtil.bind(viewHolder.itemView);
                    }

                    @Override
                    protected void convert(@NotNull BaseViewHolder baseViewHolder, @Nullable String s) {
                        FindRvLbItemBinding lbBinding = baseViewHolder.getBinding();
                        String[] temp = s.split(":");
                        lbBinding.tvLbQian.setText(temp[0].concat("："));
                        lbBinding.tvLbHou.setText(temp[1]);
                    }
                };
                adapterLb.setOnItemClickListener((adapter1, view, position) -> {
                    //                    Intent intent = new Intent(getContext(), OtherWebVIewActivity.class);
                    Bundle bundle = new Bundle();
                    String url = "";
                    if (HawkUtil.getUserId() == null) {
                        url = Constant.LOAD_WEBVIEWURL.concat(
                                String.format("/fabu/fxinfo.html?type=mobile&id=%s&uname=%s&CType=1"
                                        , findListModel.getID(), Hawk.get("uname")));
                    } else {
                        url = Constant.LOAD_WEBVIEWURL.concat(
                                String.format("/fabu/fxinfo.html?type=mobile&userid=%s&id=%s&uname=%s&CType=1"
                                        , String.valueOf(HawkUtil.getUserId()), findListModel.getID(), Hawk.get("uname")));
                    }
                    bundle.putString("url", url);
                    bundle.putString("title", "详情");

                    RouterUtils.navigate(RoutHub.WEB_MAIN, bundle, getContext());
                });
                WindowManager wm1 = getActivity().getWindowManager();
                int width1 = wm1.getDefaultDisplay().getWidth();
                tvHang = TextViewLinesUtil.getTextViewLines(binding.tvIntroduction, (width1 - DensityUtil.dip2px(getContext(), 68)));
                if (!flat) {
                    //全文
                    binding.tvShow.setText("全文");
                    binding.llPhone.setVisibility(View.GONE);
                    if (tvHang < 7) {
                        listHang = 6 - tvHang;
                        int tempIndex = listHang;
                        lbList.clear();
                        if (findListModel.getClassName().equals("二手车")) {

                            if (findListModel.getListOldcar().size() + tvHang < 6) {
                                lbList.addAll(findListModel.getListOldcar());
                                binding.tvShow.setVisibility(View.GONE);
                                binding.llPhone.setVisibility(View.VISIBLE);
                            } else {
                                binding.tvShow.setVisibility(View.VISIBLE);
                                for (String temp : findListModel.getListOldcar()) {
                                    lbList.add(temp);
                                    tempIndex--;
                                    if (tempIndex == 0) {
                                        break;
                                    }
                                }
                            }

                        } else if (findListModel.getClassName().equals("闲置品")) {
                            if (findListModel.getListXzp().size() + tvHang < 6) {
                                lbList.addAll(findListModel.getListXzp());
                                binding.tvShow.setVisibility(View.GONE);
                                binding.llPhone.setVisibility(View.VISIBLE);
                            } else {
                                binding.tvShow.setVisibility(View.VISIBLE);
                                for (String temp : findListModel.getListXzp()) {
                                    lbList.add(temp);
                                    tempIndex--;
                                    if (tempIndex == 0) {
                                        break;
                                    }
                                }
                            }

                        } else if (findListModel.getClassName().equals("商铺/写字楼")) {
                            if (findListModel.getListXzl().size() + tvHang < 6) {
                                lbList.addAll(findListModel.getListXzl());
                                binding.tvShow.setVisibility(View.GONE);
                                binding.llPhone.setVisibility(View.VISIBLE);
                            } else {
                                binding.tvShow.setVisibility(View.VISIBLE);
                                for (String temp : findListModel.getListXzl()) {
                                    lbList.add(temp);
                                    tempIndex--;
                                    if (tempIndex == 0) {
                                        break;
                                    }
                                }
                            }

                        } else if (findListModel.getClassName().equals("求购需求")) {
                            if (findListModel.getListQgxq().size() + tvHang < 6) {

                                lbList.addAll(findListModel.getListQgxq());
                                binding.tvShow.setVisibility(View.GONE);
                                binding.llPhone.setVisibility(View.VISIBLE);
                            } else {
                                for (String temp : findListModel.getListQgxq()) {
                                    lbList.add(temp);
                                    tempIndex--;
                                    if (tempIndex == 0) {
                                        break;
                                    }
                                }
                            }
                        }
                    } else {
                        binding.rvLb.setVisibility(View.GONE);
                        binding.tvIntroduction.setLines(6);
                    }
                } else {
                    //收起
                    binding.llPhone.setVisibility(View.VISIBLE);
                    binding.tvShow.setText("收起");
                    lbList.clear();
                    if (findListModel.getClassName().equals("二手车")) {
                        lbList.addAll(findListModel.getListOldcar());
                    } else if (findListModel.getClassName().equals("闲置品")) {
                        lbList.addAll(findListModel.getListXzp());

                    } else if (findListModel.getClassName().equals("商铺/写字楼")) {
                        lbList.addAll(findListModel.getListXzl());
                    } else if (findListModel.getClassName().equals("求购需求")) {
                        lbList.addAll(findListModel.getListQgxq());
                    }

                }
                binding.rvLb.setAdapter(adapterLb);
                binding.tvShow.setOnClickListener(view -> {
                    if (flat) {
                        flat = false;
                        binding.tvShow.setText("收起");
                    } else {
                        flat = true;
                        binding.tvShow.setText("全文");
                    }
                    adapter.notifyItemChanged(j);
                });
                //点赞列表
                if (findListModel.getGoodsList() != null || findListModel.getGoodsList().size() != 0) {
                    binding.tvDz.setVisibility(View.VISIBLE);
                    StringBuilder str = new StringBuilder();
                    for (int b = 0; b < findListModel.getGoodsList().size(); b++) {
                        if (!TextUtils.isEmpty(findListModel.getGoodsList().get(b).getNickName())) {
                            str.append(findListModel.getGoodsList().get(b).getNickName()).append("、");
                        }
                    }
                    if (str.length() > 1) {
                        binding.tvDz.setText(str.toString().substring(0, str.length() - 1));
                    } else {
                        binding.tvDz.setVisibility(View.GONE);
                    }

                } else {
                    binding.tvDz.setVisibility(View.GONE);
                }

                //图片合集
                binding.rvImg.setLayoutManager(new GridLayoutManager(getContext(), 3));
                RvImg();
                binding.rvImg.setAdapter(adapterImg);

                binding.tvName.setText(findListModel.getNickName());
                binding.tvIntroduction.setText(findListModel.getTitle());
                binding.tvType.setText(findListModel.getClassName());
                binding.tvBrowse.setText(findListModel.getViewCount() + "浏览");
                binding.tvShare.setText(findListModel.getShareCount() + "分享");

                binding.tvTime.setText(GetTimeAgo.getTimeAgo(Long.valueOf(TimeUtil.getTimeall(findListModel.getCreateDate())) * 1000));
                Glide.with(getContext())
                        .load(Constant.PHOTO_SERVER_URL + findListModel.getHeadUrl())
                        .error(R.drawable.default_head)
                        .circleCrop()
                        .into(binding.ivImg);
                binding.ivImg.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
//                        recyclerView.scrollToPosition(0);
                        Intent intent=new Intent(getContext(), ItFxActivity.class);
                        intent.putExtra("userid",String.valueOf(findListModel.getRUserID()));
                        startActivity(intent);
                    }
                });

                if (findListModel.getImgs() != null && findListModel != null) {
                    imgList.clear();
                    imgList.addAll(findListModel.getImgs());
                }

                //查看大图
                binding.viewImg.setOnClickListener(view -> {
                    mThumbViewInfoList.clear();
                    for (int c = 0; c < findListModel.getImgs().size(); c++) {
                        mThumbViewInfoList.add(new UserViewInfo(Constant.PHOTO_SERVER_URL + findListModel.getImgs().get(c).getPicurl()));
                    }
                    if (mThumbViewInfoList != null || mThumbViewInfoList.size() != 0) {
                        GPreviewBuilder.from(getActivity())
                                .setData(mThumbViewInfoList)
                                .setCurrentIndex(0)
                                .setDrag(false)
                                .setType(GPreviewBuilder.IndicatorType.Dot)//指示器类型
                                .setSingleFling(true)
                                .start();
                    }
                });


                //点赞分享popup
                binding.ivShare.setOnClickListener(view -> {
                    if (findListModel.getIsGood() == 1) {
                        bl = true;
                    } else {
                        bl = false;
                    }


                    dzPu(binding.tvShare, binding.tvDz, findListModel.getID(), findListModel.getIsGood(),j,findListModel.getUrl(),findListModel.getShareTitle(),findListModel.getShareDesc(),findListModel.getShareImg());


                });
                //打电话
                binding.llPhone.setOnClickListener(view -> {
                    MyUtils.callPhone(getContext(),findListModel.getPhone());
                });

            }

        };
        //跳转详情
        adapter.setOnItemClickListener((adapter1, view, position) -> {
            //            Intent intent = new Intent(getContext(), OtherWebVIewActivity.class);
            Bundle bundle1 = new Bundle();
            String url = "";

            if (HawkUtil.getUserId() == null) {
                url = Constant.LOAD_WEBVIEWURL.concat(
                        String.format("/fabu/fxinfo.html?type=mobile&id=%s&uname=%s&CType=1"
                                , list.get(position).getID(), Hawk.get("uname")));
            } else {
                url = Constant.LOAD_WEBVIEWURL.concat(
                        String.format("/fabu/fxinfo.html?type=mobile&userid=%s&id=%s&uname=%s&CType=1"
                                , String.valueOf(HawkUtil.getUserId()), list.get(position).getID(), Hawk.get("uname")));
            }
            bundle1.putString("url", url);
            bundle1.putString("title", "详情");
            RouterUtils.navigate(RoutHub.WEB_MAIN, bundle1, getContext());
        });
//        adapter.addData(list);
        viewDataBinding.recyclerView.setAdapter(adapter);

        LiveDatabus.getInstance().with("双击666").observe(this, o -> {
            viewDataBinding.recyclerView.smoothScrollToPosition(0);
        });
    }


    //图片列表
    private void RvImg() {
        adapterImg = new BaseQuickAdapter<FindListModel.ImgsBean, BaseViewHolder>(R.layout.find_rv_img_item, imgList) {

            @Override
            protected void onItemViewHolderCreated(@NotNull BaseViewHolder viewHolder, int viewType) {
                DataBindingUtil.bind(viewHolder.itemView);
            }

            @Override
            protected void convert(@NotNull BaseViewHolder baseViewHolder, FindListModel.@Nullable ImgsBean imgsBean) {
                FindRvImgItemBinding imgBinding = baseViewHolder.getBinding();
                Glide.with(getContext())
                        .load(Constant.PHOTO_SERVER_URL + imgsBean.getPicurl())
                        .thumbnail(0.1f)
                        .override(140)
                        .placeholder(R.drawable.house_bitmap)
                        .into(imgBinding.ivImgImg);

            }
        };

    }

    //点赞分享popup
    private void dzPu(View wz, TextView dz, String discoveryID, int isGood, int postaion,String url,String title,String content,String img) {
        View view = getLayoutInflater().inflate(R.layout.find_popup_like_and_share, null);
        LinearLayout like = view.findViewById(R.id.ll_like);
        LinearLayout share = view.findViewById(R.id.ll_share);
        ImageView ivLike = view.findViewById(R.id.iv_is_like);
        PopupWindow popup = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, false);
        popup.setOutsideTouchable(true);
        popup.setTouchable(true);
        popup.setFocusable(true);
        PopupWindowCompat.showAsDropDown(popup, wz, -40, -90, Gravity.END);

        if (bl) {
            ivLike.setImageResource(R.drawable.ic_like);
        } else {
            ivLike.setImageResource(R.drawable.ic_no_like);
        }

        like.setOnClickListener(view1 -> {
            if (HawkUtil.getUserId() == null) {
                MyUtils.myShowDialog(getContext());
                return;
            }
            if (!bl) {
                String dzText = dz.getText().toString();
                if (TextUtils.isEmpty(dzText)) {
                    dz.setText(Hawk.get("alias"));
                } else {
                    dz.setText(dzText.concat("、").concat(Hawk.get("alias")));
                }
                ivLike.setImageResource(R.drawable.ic_like);
                bl = true;
            } else {
                String dzText = dz.getText().toString();
                if (StringTest.countStr(dz.getText().toString(), "、") == 0) {
                    String newStr = dzText.replace(Hawk.get("alias"), "");
                    dz.setText(newStr);
                } else {
                    if (!dz.getText().toString().contains("、" + Hawk.get("alias"))) {
                        if (!dz.getText().toString().contains(Hawk.get("alias") + "、")) {
                            String newStr = dzText.replace(Hawk.get("alias"), "");
                            dz.setText(newStr);
                        } else {
                            String newStr = dzText.replace(Hawk.get("alias") + "、", "");
                            dz.setText(newStr);
                        }

                    } else {
                        String newStr = dzText.replace("、" + Hawk.get("alias"), "");
                        dz.setText(newStr);
                    }

                }
                ivLike.setImageResource(R.drawable.ic_no_like);
                bl = false;
            }
            if (TextUtils.isEmpty(dz.getText().toString())) {
                dz.setVisibility(View.GONE);
            } else {
                dz.setVisibility(View.VISIBLE);
            }
            dzShare(1, discoveryID, postaion);

        });
        share.setOnClickListener(view1 -> {
            if (HawkUtil.getUserId() == null) {
                MyUtils.myShowDialog(getContext());
                return;
            }
//            dzShare(2, discoveryID,postaion);
            add(discoveryID, 2);
            MyUtils.shareDialog(getContext(),url,title,content,img);
            popup.dismiss();
        });

    }

    /**
     * 数据刷新和加载更多
     */
    private void thisClick() {
        init();
        //设置内容不满一页时禁用加载更多
        viewDataBinding.swipeRefresh.setEnableLoadMoreWhenContentNotFull(true);
        viewDataBinding.swipeRefresh.setOnLoadMoreListener(refreshLayout -> {
            index++;
            flat = false;
            loadData(findListPar);
        });
        viewDataBinding.swipeRefresh.setOnRefreshListener(refreshLayout -> {
            index = 1;
            flat = false;
            loadData(findListPar);
        });

    }

    /**
     * 请求数据
     *
     * @param par
     */
    public void loadData(FindListPar par) {
        par.setPageIndex(index);
        EasyHttp.post(HttpConfig.getFindList)
                .cacheKey(HttpConfig.getFindList)
                .upJson(GsonUtils.toJson(par))
                .execute(new SimpleCallBack<List<FindListModel>>() {
                    @Override
                    public void onSuccess(List<FindListModel> findListModels) {
                        if (index == 1) {
                            list.clear();
                            if (findListModels == null || findListModels.size() == 0) {
                                viewDataBinding.icNoData.setVisibility(View.VISIBLE);
                            } else {
                                viewDataBinding.icNoData.setVisibility(View.GONE);
                                if (findListModels.size() < 5) {
                                    viewDataBinding.swipeRefresh.setNoMoreData(true);
                                }
                            }
                            list.addAll(findListModels);
                            adapter.notifyDataSetChanged();
                        } else {
                            int start = list.size();
                            list.addAll(findListModels);
                            adapter.notifyItemInserted(start);
                            if (findListModels.size() < 5) {
                                viewDataBinding.swipeRefresh.finishLoadMoreWithNoMoreData();
                            }
                        }
                    }

                    @Override
                    public void onError(ApiException e) {

                    }

                    @Override
                    public void onCompleted() {
                        viewDataBinding.swipeRefresh.finishLoadMore();
                        viewDataBinding.swipeRefresh.finishRefresh();
                    }
                });


    }

    private void add(String id, int ctype) {
        SinglePar singlePar = new SinglePar();
        singlePar.setID(id);
        singlePar.setRUserID(String.valueOf(HawkUtil.getUserId()));
        singlePar.setCtype(ctype);
        EasyHttp.post(HttpConfig.addDiscount)
                .cacheKey(HttpConfig.addDiscount)
                .upJson(GsonUtils.toJson(singlePar))
                .execute(new SimpleCallBack<Boolean>() {
                    @Override
                    public void onSuccess(Boolean aBoolean) {

                    }

                    @Override
                    public void onError(ApiException e) {

                    }

                    @Override
                    public void onCompleted() {

                    }
                });
    }

    public void dzShare(int ctype, String discoveryID, int postaion) {
        NewSharePar newSharePar = new NewSharePar();
        newSharePar.setCtype(ctype);
        newSharePar.setRUserID(String.valueOf(HawkUtil.getUserId()));
        newSharePar.setDiscoveryID(discoveryID);
        EasyHttp.post(HttpConfig.getNewShare)
                .cacheKey(HttpConfig.getNewShare)
                .upJson(GsonUtils.toJson(newSharePar))
                .execute(new SimpleCallBack<Boolean>() {
                    @Override
                    public void onSuccess(Boolean aBoolean) {

                    }

                    @Override
                    public void onError(ApiException e) {

                    }

                    @Override
                    public void onCompleted() {

                    }
                });


    }


    @Override
    public int getBindingVariable() {
        return 0;
    }

    @Override
    protected IMvvmBaseViewModel getViewModel() {
        return null;
    }

    @Override
    protected void onRetryBtnClick() {

    }
}
